package cool.mtc.web.annotation.serializer.enums;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import cool.mtc.core.util.StringUtil;
import cool.mtc.web.component.dict.EnumDictStyleColorSupport;
import cool.mtc.web.component.dict.EnumDictSupport;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author 明河
 * <p>
 * 枚举字典数据序列化
 */
@Slf4j
public class EnumDictSerializer extends StdSerializer<Object> implements ContextualSerializer {
    private static final String VALUE_FIELD_NAME_SUFFIX = "Name";
    private static final String STYLE_COLOR_FIELD_NAME_SUFFIX = "StyleColor";

    private String displayNameFieldName;
    private String styleColorFileName;

    public EnumDictSerializer() {
        super(Object.class);
    }

    public EnumDictSerializer(String displayNameFieldName, String styleColorFileName) {
        super(Object.class);
        this.displayNameFieldName = displayNameFieldName;
        this.styleColorFileName = styleColorFileName;
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property) {
        EnumDict annotation = property.getAnnotation(EnumDict.class);
        return new EnumDictSerializer(annotation.displayNameFieldName(), annotation.styleColorFileName());
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        // 原字段值
        gen.writeObject(value);
        String valueFieldName = gen.getOutputContext().getCurrentName();

        String fieldName;
        if (value instanceof EnumDictSupport) {
            fieldName = StringUtil.ifEmpty(this.displayNameFieldName, valueFieldName + VALUE_FIELD_NAME_SUFFIX);
            gen.writeObjectField(fieldName, ((EnumDictSupport) value).getDisplayName());
        }

        if (value instanceof EnumDictStyleColorSupport) {
            fieldName = StringUtil.ifEmpty(this.styleColorFileName, valueFieldName + STYLE_COLOR_FIELD_NAME_SUFFIX);
            gen.writeObjectField(fieldName, ((EnumDictStyleColorSupport) value).getStyleColor());
        }
    }
}
